<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class member_permission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( Request $request, Closure $next )
    {
        // 执行路由
        $execute_router = str_replace( '\\', '/', $request->route()->getAction( 'controller' ) );

        // 路由器
        $router = explode( '@', $execute_router );

        // 控制器
        $controller = $router[ 0 ];

        // 行为
        $action = $router[ 1 ];
        // 获取权限
        if( ( $member = $request->member ) && isset( $member[ 'authorization' ] ) && ( $member[ 'authorization' ] !== '*' ) )
        {
            // 权限列表
            $authorization = json_decode( $member[ 'authorization' ], true );
            
            // 是否有授权
            if( ! isset( $authorization[ $controller ] ) || ( $authorization[ $controller ] != '*' && ! in_array( $action, $authorization[ $controller ] ) ) )
            {
                return response()->json( [ 'code' => 10009, 'message' => 'no access' ] );
            }
        }

        return $next( $request );
    }
}